const router = require('koa-router')();
router.prefix(appConfig.authPrefixUrl+'/desktop/index');
const SysUserService = appRequire('service/desktop/SysUserService.js');
const IndexVo = appRequire('vo/index/IndexVo.js');
const ResultVo = appRequire('vo/ResultVo.js');
router.get('/init',async(ctx)=>{
  let indexVo = new IndexVo();
  let ses_user = ctx.session.user;
  let user = {};
  if (ses_user) {
    let mem_user =appConfig.db[ses_user.username];
    if(!mem_user){
      let data = await SysUserService.findUserAuthItem(ses_user.id);
      user.authUrls = data.authUrls;
      user.menuInfo = data.authMenus;
      appConfig.db[user.username] = user;
    }else{
      user = mem_user;
    }
  }
  console.log("indexC20.......................");
  console.log(user);
  indexVo.vo.menuInfo = user.menuInfo;
  ctx.body=indexVo.vo;
});
router.post('/updateUserInfo',async(ctx)=>{
  try{
    let header = ctx.request.header;
    console.log(header);
    let user = ctx.request.body;
    console.log(user);
    await SysUserService.save(user);
    ctx.body = ResultVo.success('success');
  }catch(err){
    //集中处理错误
    err.msg = "修改用户详情失败!";
    ctx.app.emit('error', err, ctx);
  }
});
router.get('/findOne',async(ctx)=>{
  try{
    let ses_user = ctx.session.user;
    let user = await SysUserService.findOne(ses_user.id);
    ctx.body = ResultVo.success('success',user);
  }catch(err){
    //集中处理错误
    err.msg = "查找用户失败!";
    ctx.app.emit('error', err, ctx);
  }
});
router.post('/updatePassword',async(ctx)=>{
  try{
    let pam_user = ctx.request.body;
    let ses_user = ctx.session.user;
    console.log(pam_user);
    console.log(ses_user);
    console.log(ses_user.username,pam_user.old_password);
    let user = {username:ses_user.username,password:pam_user.old_password};
    user = await SysUserService.findOneByUsernameAndPassword(user);
    if(user&&user.password&&pam_user.old_password===user.password){
      user.password = pam_user.again_password
      await SysUserService.save(user);
      user.password = "";
      ctx.body = ResultVo.success('success',user);
    }else{
      throw new Error();
    }
  }catch(err){
    //集中处理错误
    err.msg = "更新用户密码失败!";
    ctx.app.emit('error', err, ctx);
  }
});
module.exports = router;